package org.kinglone.back.comment.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.transform.ResultTransformer;
import org.kinglone.back.comment.model.Comment;
import org.kinglone.common.dao.impl.BaseDaoImpl;
import org.kinglone.common.util.PageQuery;
import org.kinglone.common.util.PageResults;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("commentService")
@Transactional(readOnly=false)
public class CommentServiceImpl extends BaseDaoImpl<Comment> implements CommentService{

	@Override
	public PageResults<Comment> commentList(PageQuery pageQuery) {
		
		String hql ="from Comment c order by c.createTime desc";
		
		String countHql="select count(0) from Comment";
		
		PageResults<Comment> pageResults =  super.findPageByFetchedHql(hql, countHql, pageQuery, null);
		return pageResults;
					
	}

	@Override
	public List<Comment> getByArticleId(String id) {
		String sql = "select c.sysid,c.content,c.createtime,c.nickname from comment c where c.articleId =?";
		Query query = this.getSession().createSQLQuery(sql);
		query.setParameter(0, id);		
		List<Object[]> list = query.list();
		List<Comment> comments = new ArrayList<Comment>();
		for (Object[] objects : list) {
			Comment c = new Comment();
			c.setSysid(objects[0].toString());
			c.setContent(objects[1].toString());
			c.setCreateTime(objects[2].toString());
			c.setNickname(objects[3].toString());
			comments.add(c);
		}
		
		return comments;
	}

	@Override
	public BigInteger getCountByArticleId(String sysid) {
		String sql = "select IFNULL(count(*),0) from comment where articleId =?";
		Query query = this.getSession().createSQLQuery(sql);
		query.setParameter(0, sysid);
		return (BigInteger)query.list().get(0);
	}

	@Override
	public List<Comment> getCommentByNum() {
		String sql = "select c.sysid,c.content,c.createtime from comment c ,article a  where c.articleId =a.sysid  AND a.isDisplay ='Y' order by c.createtime  desc limit 5";
		Query query = this.getSession().createSQLQuery(sql);
		List<Object[]> list = query.list();
		List<Comment> comments = new ArrayList<Comment>();
		for (Object[] objects : list) {
			Comment c = new Comment();
			c.setSysid(objects[0].toString());
			c.setContent(objects[1].toString());
			c.setCreateTime(objects[2].toString());
			comments.add(c);
		}
		
		return comments;
	}

}
